package org.example.servlet;

import org.example.entity.Review;
import org.example.entity.User;
import org.example.service.ReviewService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/AddReviewServlet")
public class AddReviewServlet extends HttpServlet {
    private final ReviewService reviewService = new ReviewService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(false);

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                response.sendRedirect(request.getContextPath() + "/Userlogin.jsp");
                return;
            }

            // 2. 获取表单数据
            int contentId = Integer.parseInt(request.getParameter("contentId"));
            String contentType = request.getParameter("contentType");
            int rating = Integer.parseInt(request.getParameter("rating"));
            String comment = request.getParameter("comment");

            // 3. 验证评分范围 (1-5)
            if (rating < 1 || rating > 5) {
                throw new IllegalArgumentException("评分必须在1-5之间");
            }

            // 4. 获取用户信息
            User user = (User) session.getAttribute("user");
            if (user == null) {
                throw new IllegalStateException("用户信息不存在");
            }

            // 5. 创建评论对象
            Review review = new Review();
            review.setContentId(contentId);
            review.setContentType(contentType);
            review.setUserId(user.getId());
            review.setUsername(user.getUsername());
            review.setRating(rating);
            review.setContent(comment);
            review.setIsAnonymous(false); // 默认非匿名
            review.setIpAddress(request.getRemoteAddr());

            // 6. 检查用户是否已经评论过
            Review existingReview = reviewService.getReviewByUserAndContent(
                    user.getId(), contentId, contentType);

            boolean success;
            if (existingReview != null) {
                // 更新现有评论
                existingReview.setRating(rating);
                existingReview.setContent(comment);
                success = reviewService.updateReview(existingReview);
            } else {
                // 添加新评论
                success = reviewService.addReview(review);
            }

            // 7. 处理结果
            if (success) {
                session.setAttribute("reviewSuccess", "评论提交成功！");
                String redirectUrl = request.getContextPath() +
                        "/content/detail?id=" + contentId + "&type=" + contentType;
                response.sendRedirect(redirectUrl);
            } else {
                request.setAttribute("error", "评论提交失败，请稍后再试");
                request.getRequestDispatcher("/error.jsp").forward(request, response);
            }

        } catch (NumberFormatException e) {
            handleError(request, response, "无效的数字格式", e);
        } catch (IllegalArgumentException e) {
            handleError(request, response, e.getMessage(), e);
        } catch (SQLException e) {
            handleError(request, response, "数据库错误，请稍后再试", e);
        } catch (Exception e) {
            handleError(request, response, "服务器错误，请稍后再试", e);
        }
    }

    private void handleError(HttpServletRequest request, HttpServletResponse response,
                             String message, Exception e) throws ServletException, IOException {
        e.printStackTrace();
        request.setAttribute("error", message);
        request.getRequestDispatcher("/error.jsp").forward(request, response);
    }
}